package com.hronline;

import com.parser.LoginParser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint("CommitPrefEdits")
public class PasscodeActivity extends Activity {

	EditText 	edtPass1;
	EditText 	edtPass2;
	EditText 	edtPass3;
	EditText 	edtPass4;
	EditText	edtPass5;
	TextView	txtInstruction;
	TextView	txtFailAttempt;
	
	boolean		isSetupPasscode;
	int			failAttemptCount = 0;
	
	public final int MAX_ATTEMPT	=	10;	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_passcode);
		
		/* get all controls and assign selector to them */
		setUpView();
		
		/* check view to show */
		checkViewToShow();
	}
	
	/* INIT VIEW
	 * this section is used to set up view for this activity
	 *  */
	
	/* this method is used to set up control and assign selector for control on view */
	private void setUpView(){
		
		SharedPreferences preferences	=	this.getSharedPreferences(Constant.MY_PREFERENCES, MODE_PRIVATE);
		Constant.currentUser	=	LoginParser.parseUserInfo(preferences.getString(Constant.USER_INFO, ""));
		
		/* get editText */
		edtPass1	=	(EditText)findViewById(R.id.edtPass1);
		edtPass2	=	(EditText)findViewById(R.id.edtPass2);
		edtPass3	=	(EditText)findViewById(R.id.edtPass3);
		edtPass4	=	(EditText)findViewById(R.id.edtPass4);
		edtPass5	=	(EditText)findViewById(R.id.edtPass5);
		
		/* set next focus */
		edtPass1.setNextFocusRightId(R.id.edtPass2);
		edtPass2.setNextFocusRightId(R.id.edtPass3);
		edtPass3.setNextFocusRightId(R.id.edtPass4);
		edtPass4.setNextFocusRightId(R.id.edtPass5);
		
		/* assign the selector for each pass code box */
		assignFocusable();
		edtPass1.requestFocus();
		
		/* get text Instruction */
		txtInstruction	=	(TextView)findViewById(R.id.txtInstruction);
		txtFailAttempt	=	(TextView)findViewById(R.id.txtFailAttemp);
		
		//hidden the fail attempt
		txtFailAttempt.setVisibility(View.INVISIBLE);
	}
	
	/*
	 * SELECTOR
	 * this section is used to implement selector for this activity
	 * */
	
	/* this method is used to set which passcode box will be move next */
	private void assignFocusable(){
		
		edtPass1.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				moveToTheNextPassCodeBox(1);
			}
		});
		
		edtPass2.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				moveToTheNextPassCodeBox(2);
			}
		});
		
		edtPass3.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				moveToTheNextPassCodeBox(3);
			}
		});
		
		edtPass4.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				moveToTheNextPassCodeBox(4);
			}
		});
		
		edtPass5.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(edtPass5.getText().length() > 0)
				{
					if(isSetupPasscode){
						displayAnimation();
					}
					else{
						String pincode	=	String.format("%s%s%s%s%s", edtPass1.getText().toString(), edtPass2.getText().toString(), edtPass3.getText().toString(), edtPass4.getText().toString(), edtPass5.getText().toString());
						
						//match
						if(validatePinCode(pincode)){
							showDashboardPage();
						}
						else{//not match
							failAttemptCount++;
							if(failAttemptCount == MAX_ATTEMPT){//back to the login activity
								showLoginPage();
							}
							else{
								displayAnimation();
							}
						}
					}
				}
			}
		});
	}
	
	/* this method is used to move to next pass code box when user enter character */
	private void moveToTheNextPassCodeBox(int index)
	{
		switch (index) {
		case 1:
			edtPass2.requestFocus();
			break;
			
		case 2:
			edtPass3.requestFocus();
			break;
			
		case 3:
			edtPass4.requestFocus();
			break;
			
		case 4:
			edtPass5.requestFocus();
			break;
		}
	}
	
	/* this method is used to check which view should be show: set up pass code or confirm pass code */
	private void checkViewToShow(){
		SharedPreferences preferences	=	this.getSharedPreferences(Constant.MY_PREFERENCES, MODE_PRIVATE);
		String pincode					=	preferences.getString(Constant.MY_PIN_CODE, "");
		if(pincode.length() > 0){
			isSetupPasscode	= false;
			txtInstruction.setText(Constant.REQUIRE_PIN_CODE);
		}
		else{
			isSetupPasscode = true;
		}
			
	}
	
	/* this method is used to get the size of device */
	private Point getDisplaySize(Display display) {
	    Point point = new Point();
	    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){    
	        return point;
	    }else{    
	        point.x = display.getWidth();
	        point.y = display.getHeight();
	    }
	    return point;
	}
	
	/* this method is used to display animation */
	private void displayAnimation(){
		/* get size of device screen */
		Display display = getWindowManager().getDefaultDisplay();
		Point size	=	getDisplaySize(display);
		int width = size.x;
		
		View rootView	=	findViewById(R.id.passcode_root_view);
		TranslateAnimation anim	=	new TranslateAnimation(0, -width, 0, 0);
		anim.setDuration(700);
		anim.setAnimationListener(new AnimationListener() {
			
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				if(isSetupPasscode){
					savingSetUpPasscode();
					showConfirmPasscodeView();
				}
				else{
					showingAttemptFail();
				}
			}
		});
		rootView.startAnimation(anim);
	}
	
	/* this method is used to saving pass code */
	private void savingSetUpPasscode(){
		//saving pin code
		String pincode	=	String.format("%s%s%s%s%s", edtPass1.getText().toString(), edtPass2.getText().toString(), edtPass3.getText().toString(), edtPass4.getText().toString(), edtPass5.getText().toString());
		
		SharedPreferences preferences	=	PasscodeActivity.this.getSharedPreferences(Constant.MY_PREFERENCES, MODE_PRIVATE);
		SharedPreferences.Editor editor	=	preferences.edit();
		editor.putString(Constant.MY_PIN_CODE, pincode);
		editor.commit();
		
		isSetupPasscode	=	false;
	}
	
	/* this method is used to reset pass code box */
	private void resetPasscodeBox(){
		edtPass1.setText("");
		edtPass2.setText("");
		edtPass3.setText("");
		edtPass4.setText("");
		edtPass5.setText("");
	}
	
	/* this method is used to slide to the confirm pass code view */
	private void showConfirmPasscodeView(){
		
		resetPasscodeBox();
		edtPass1.requestFocus();
		txtInstruction.setText(R.string.text_confirm_pin_code);
	}
	
	/* this method is used to validate the pin code */
	private boolean validatePinCode (String pincode){
		
		SharedPreferences preferences	=	this.getSharedPreferences(Constant.MY_PREFERENCES, MODE_PRIVATE);
		String savedPincode	=	preferences.getString(Constant.MY_PIN_CODE, "");
		
		//match
		if(savedPincode.compareToIgnoreCase(pincode) == 0)
		{
			return true;
		}
	
		return false;
	}
	
	/* this method is used to show attempt fail */
	private void showingAttemptFail(){
		resetPasscodeBox();
		
		edtPass1.requestFocus();
		txtInstruction.setText(Constant.PIN_CODE_NOT_MATCH);
		txtFailAttempt.setVisibility(View.VISIBLE);
		txtFailAttempt.setText(String.format("%d %s", failAttemptCount, Constant.FAIL_ATTEMPT));
	}
	
	/* this method is used to back into login activity */
	private void showLoginPage(){
		
		/* reset all user info in app */
		Constant.resetAllUserDataCaching(this, MODE_PRIVATE);
		
		/* open login page */
		Intent intent	=	new Intent(this, LoginActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		this.startActivity(intent);
		
		/* destroy this activity */
		finish();
		
	}
	
	/* this method is used to show dashboard page */
	private void showDashboardPage(){
		Intent intent;
		
		/* user is manager */
//		if(Constant.currentUser.getPosition().compareToIgnoreCase(Constant.MANAGER_POSTION) == 0){
//			intent	=	new Intent(this, ManagerDashboardActivity.class);
//		}
//		else{ //user is employee
//			intent	=	new Intent(this, EmployeeDashboardActivity.class);	
//		}
		intent	=	new Intent(this, TabbarActivity.class);
		this.startActivity(intent);
		
		//destroy this
		finish();
	}
	
}
